<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info"
                  show-icon/>

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('vip.code.quick Search Fields') })"
        >
            <el-button v-blur class="table-header-operate" type="success" style="margin-left: 12px" @click="derive">
                <Icon color="#ffffff" name="el-icon-Download"/>
                <span class="table-header-operate-text">导出</span>
            </el-button>

            <el-button v-blur class="table-header-operate" type="info" style="margin-left: 12px" @click="batchTransfer">
                <Icon color="#ffffff" name="el-icon-Download"/>
                <span class="table-header-operate-text">批量转拨</span>
            </el-button>


            <el-button v-blur class="table-header-operate" :disabled="baTable.getSelectionIds().length === 0" type="danger" style="margin-left: 12px" @click="freeze">
                <Icon color="#ffffff" name="el-icon-CloseBold"/>
                <span class="el-icon-CloseBold">冻结</span>
            </el-button>

            <el-button v-blur class="table-header-operate" :disabled="baTable.getSelectionIds().length === 0" type="success" style="margin-left: 12px" @click="unhitch">
                <Icon color="#ffffff" name="el-icon-Check"/>
                <span class="table-header-operate-text">解冻</span>
            </el-button>
        </TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef"></Table>

        <!-- 表单 -->
        <PopupForm/>

        <BatchTransfer />
    </div>
</template>

<script setup lang="ts">
import {onMounted, provide, ref} from 'vue'
import {useI18n} from 'vue-i18n'
import PopupForm from './popupForm.vue'
import {baTableApi} from '/@/api/common'
import {defaultOptButtons} from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import createAxios from "/@/utils/axios";
import {AxiosPromise} from 'axios'
import fileDownload from 'js-file-download'
import {ElMessage, ElMessageBox} from 'element-plus'; // 导入 Element UI 的 Message 和 MessageBox 组件
import BatchTransfer from './batchTransfer.vue'
defineOptions({
    name: 'vip/code',
})

const {t} = useI18n()
const tableRef = ref()
const optButtons: OptButton[] = defaultOptButtons(['delete'])

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/vip.Code/'),
    {
        pk: 'id',
        column: [
            {type: 'selection',label: '起止',prop: 'id', align: 'center', operator: 'RANGE'},
            {label: t('vip.code.id'), prop: 'id', align: 'center', width: 70, operator: false, sortable: 'custom'},
            {
                label: "代理商",
                prop: 'admin.nickname',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                render: 'tags',
                width: 150,
                showOverflowTooltip:true,
                operator: 'LIKE'
            },
            {
                label: t('vip.code.vipcard__name'),
                prop: 'vipCard.name',
                align: 'center',
                width: 120,
                operatorPlaceholder: t('Fuzzy query'),
                render: 'tags',
                operator: 'LIKE',

            },

            {
                label: t('vip.code.number'),
                prop: 'number',
                width: 120,
                align: 'center',
                operator: 'LIKE',
                sortable: false
            },
            {
                label: t('vip.code.password'),
                prop: 'password',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                operator: false,
                sortable: false
            },
            {
                label: t('冻结'),
                prop: 'is_freeze',
                align: 'center',
                render: 'tag',
                operator: 'eq',
                sortable: false,
                custom: { '0': 'success', '1': 'danger' },
                replaceValue: {'0': t('正常'), '1': t('冻结')}
            },

            {
                label: t('冻结原因'),
                prop: 'reason',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                operator: false,
                width: 120,
                showOverflowTooltip: true,
                sortable: false
            },


            {
                label: t('vip.code.radio'),
                prop: 'status',
                align: 'center',
                render: 'tag',
                operator: 'eq',
                sortable: false,
                custom: { '0': 'danger', '1': 'success','2':'info' },

                replaceValue: {'0': t('vip.code.radio 0'), '1': t('vip.code.radio 1'),'2':'已过期'}
            },

            {
                label: "最后使用时间",
                prop: 'user_expire_time',
                align: 'center',
                render: 'datetime',
                operator: false,
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss'
            },

            {
                label: t('vip.code.create_time'),
                prop: 'create_time',
                align: 'center',
                render: 'datetime',
                operator: false,
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss'
            },
            {
                label: t('vip.code.update_time'),
                prop: 'update_time',
                align: 'center',
                render: 'datetime',
                operator: false,
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss'
            },
            {label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false},
        ],
        dblClickNotEditColumn: ['all'],
    },
    {
        defaultItems: {radio: '0'},
    }
)

provide('baTable', baTable)


const batchTransfer = async () => {
    baTable.form.operate = 'BatchTransfer'
}



const freeze = async () => {
    let SelectionIds = baTable.getSelectionIds()
    if(SelectionIds.length == 0){
        ElMessage.error('请选择冻结项')
        return false;
    }

    try {
        const { value: freezeReason } = await ElMessageBox.prompt('请输入冻结原因', '冻结确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPlaceholder: '请输入冻结原因',
            inputValidator: (value) => {
                if (!value) {
                    return '冻结原因不能为空'
                }
                return true
            },
            type: 'warning'
        })

        const res = await toFreeze(freezeReason);
        ElMessage.success(res.msg)
        baTable.onTableHeaderAction('refresh', {})
    } catch (e) {
        // 用户取消操作
        if (e !== 'cancel') {
            ElMessage.error('操作失败')
        }
    }
}


const unhitch = async () => {
    let SelectionIds = baTable.getSelectionIds()
    if(SelectionIds.length == 0){
        ElMessage.error('请选择解冻项')
        return false;
    }

    try {
        await ElMessageBox.confirm('确定要解冻所选项吗？', '解冻确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const res = await toUnhitch();
        ElMessage.success(res.msg)
        baTable.onTableHeaderAction('refresh', {})
    } catch (e) {
        // 用户取消操作
    }
}


const toFreeze = (reason: string) => {
    return createAxios(
        {
            url: '/admin/vip.Code/freeze',
            method: 'POST',
            data:{
                ids: baTable.getSelectionIds(),
                reason: reason
            }
        },{
            loading:true
        }
    );
};

const toUnhitch = () => {
    return createAxios(
        {
            url: '/admin/vip.Code/unhitch',
            method: 'POST',
            data:{ids: baTable.getSelectionIds()}
        },{
            loading:true
        }
    );
};




const derive = () => {
    let comSearchData = baTable.getComSearchData()
    createAxios<any, AxiosPromise>(
        {
            url: '/admin/vip.Code/addExportTask',
            method: 'get',
            responseType: 'blob',
            timeout: 0,
            params: {
                search: comSearchData,
            },
        },
        {
            showErrorMessage:true,
            loading:true,
        }
    ).then((response) => {
        ElMessage.success('导出成功，请在导出管理查看')
    })
}



onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

<style scoped lang="scss"></style>
